package com.example.tutorial.java.concurrent;


/**
 * 为每一个线程都提供一个变量的副本，使得每一个线程在某一个时刻访问到的不是同一个对象
 *
 * @author: cph
 * @date: 2022-4-16
 */
public class ThreadLocalTest {

    private static ThreadLocal<String> local = new ThreadLocal<>();

    static void print(String str) {
        System.out.println(str + ": " + local.get());
        local.remove();
    }

    public static void main(String[] args) throws Exception {
        new Thread(new Runnable() {
            @Override
            public void run() {
                ThreadLocalTest.local.set("class_A");
                print("A");
                System.out.println("after remove(): " + local.get());
            }
        }, "A").start();

        Thread.sleep(1000);

        new Thread(new Runnable() {
            @Override
            public void run() {
                ThreadLocalTest.local.set("class_B");
                print("B");
                System.out.println("after remove(): " + local.get());
            }
        }).start();


    }
}
